import React, { useEffect } from 'react';
import { useMutation, useApolloClient } from '@apollo/client';
import { SIGNIN_USER } from '../gql/mutation';

import UserForm from '../components/UserForm';


const SignIn = props => {
    useEffect(() => {
        document.title = 'Sign In —— Notedly';
    });
    
    const client = useApolloClient();
    const [ signIn, { loading, error }] = useMutation(SIGNIN_USER, {
        onCompleted: data => {
            //把JWT存储的LocalStorage中
            localStorage.setItem('token', data.signIn);
            //更新本地缓存
            client.writeData({ data: { isLoggedIn: true } });
            //把用户重定向到首页
            props.history.push('/');
        }
    });

    return(
        <React.Fragment>
            <UserForm action={signIn} formType="signIn"></UserForm>
            {loading && <p>Loading...</p>}
            {error && <p>Error signing in!</p>}
        </React.Fragment>
    );
};

export default SignIn;